#include <setjmp.h>
#include <stdio.h>
#include <stdlib.h>

/* functions divides i and j
 * jmp_buf env is the environment for 
 * error handling (divide by zero error)
 */
int divide(jmp_buf env, int i, int j)
{
  if (j == 0) longjmp(env, 1);
  return i / j;
}

/* Main program shows usage of setjmp()/longjmp() for
 * error handling.
 * It is easy to image different return values for 
 * different error codes that can be handled in a
 * switch.
 */
int main(int argc, char **argv)
{
  
    //buffer for setjmp()/longjmp()
    //stores registers
    jmp_buf env;
    //return value of setjmp()
    //0 if called first time -> store environment
    //different from 0 else
    int sj;
    //some local variables for the arguments
    int i, j;

    //we need two arguments + counter
    if (argc != 3) {
	fprintf(stderr, "You need two integers as parameter.\n");
	exit(1);
    }
    
    //save context
    sj = setjmp(env);
    //if we go here by longjmp(), there has been an error
    //print error message
    if (sj != 0) {
	printf("Bad value: can`t divide by zero.\n");
	exit(0);
    }

    //get values
    i = atoi(argv[1]);
    j = atoi(argv[2]);

    //if function works, print the result
    printf("divide(%d, %d) = %d\n", i, j, divide(env, i, j));
}
  

